from odoo import models, fields, api, _
from odoo.exceptions import ValidationError


class EquipmentRequisition(models.Model):
    _name = 'equipment.requisition'
    _inherit = ['portal.mixin', 'mail.thread.main.attachment', 'mail.activity.mixin']
    _description = 'Equipment Requisition'

    name = fields.Char(string='PR Name', required=True, default='New', index=True)
    # 设备类型
    # equipment_type = fields.Char(string='Equipment Type')
    equipment_type_id = fields.Many2one('equipment.type', string='Equipment Type')
    # 设备名称
    equipment_name = fields.Char(string='Equipment Name')
    # 设备数量
    equipment_qty = fields.Integer(string='Equipment Qty')
    # 需求背景描述
    description = fields.Text(string='Description')
    # 申请人
    user_id = fields.Many2one('res.users', string='User', default=lambda self: self.env.user)
    # 申请部门
    department_id = fields.Many2one('hr.department', string='Department',
                                    default=lambda self: self.env.user.department_id)
    # 请购日期
    date = fields.Date(string='Date', default=fields.Date.today)
    type = fields.Selection([
        ('engineering', 'Engineering'),
        ('equipment', 'Equipment')
    ], string='Type', default='equipment')
    state = fields.Selection([
        ('draft', 'Draft'),
        ('wait_approval', 'Waiting for Approval'),
        ('approved', 'Approved'),
        ('rejected', 'Rejected')
    ], default='draft', string='Status', tracking=True)
    remark = fields.Text(string='Remark')
    s_document_ids = fields.One2many('documents.document', 'res_id', string='Documents',
                                     domain="[('res_model', '=', 'equipment.requisition'), ('res_id', '=', id)]")
    # 审批相关
    sb_workflow_template_id = fields.Many2one('sb.workflow.template', string="Approval Workflow Template",
                                              domain="[('sb_workflow_template_item_ids', '!=', False),"
                                                     "('workflow_type', '=', 'purchase_requisition')]")
    sb_workflow_id = fields.Many2one('sb.workflow', string="Current Approval Workflow", copy=False)
    sb_workflow_state = fields.Selection(related="sb_workflow_id.state",
                                         readonly=True, store=True,
                                         string="Approval Status")
    sb_workflow_item_ids = fields.One2many(related="sb_workflow_id.sb_workflow_item_ids", string="Approval Items")
    sb_workflow_attachments_ids = fields.One2many(related="sb_workflow_id.sb_workflow_attachments_ids",
                                                  string="Approval Attachments")
    sb_workflow_ids = fields.One2many('sb.workflow', 'equipment_id', string="Approval Workflows")

    def create_workflow(self):
        if self.sb_workflow_template_id:
            if len(self.sb_workflow_ids) > 0:
                workflow_sum = len(self.sb_workflow_ids) + 1
            else:
                workflow_sum = 1
            self.state = 'wait_approval'
            if self.name == 'New' or not self.name:
                if self.type == 'equipment':
                    self.name = self.env['ir.sequence'].next_by_code('equipment.requisition.prs')
                    self.message_post(body=_('Submit for approval'))
                elif self.type == 'engineering':
                    self.name = self.env['ir.sequence'].next_by_code('equipment.requisition.pre')
                    self.message_post(body=_('Submit for approval'))
            # 创建审批流
            new_wf_id = self.env['sb.workflow'].sudo().create({
                'name': self.name + '- Approval Flow' + '-' + str(workflow_sum),
                'approval_time': fields.Datetime.now(),
                'workflow_type': 'purchase_requisition',
                'equipment_id': self.id,
                'remark': self.remark or ''
            })
            self.sb_workflow_id = new_wf_id.id
            # 根据模板生成审批项
            item_audit_levels = []
            for item in self.sb_workflow_template_id.sb_workflow_template_item_ids:
                new_item = self.env['sb.workflow.item'].sudo().create({
                    'name': item.name,
                    'user_group_ids': item.user_group_ids.ids,
                    'audit_level': item.audit_level,
                    'sb_workflow_id': new_wf_id.id,
                    'state': 'wait_forward'
                })
                # 收集生成的审核项的所有层级
                item_audit_levels.append(new_item.audit_level)
            # 去重排序
            item_audit_levels = list(set(item_audit_levels))
            item_audit_levels.sort()
            # 开放最低层级的神匹配
            for n_item in new_wf_id.sb_workflow_item_ids:
                if n_item.audit_level == item_audit_levels[0]:
                    n_item.state = 'approval'
        else:
            raise ValidationError(_('Please select an approval template.'))

    def action_view_workflow(self):
        return {
            'name': _('Approval Flow'),
            'type': 'ir.actions.act_window',
            'res_model': 'sb.workflow',
            'view_mode': 'tree,form',
            'target': 'current',
            'domain': [('equipment_id', '=', self.id)],
        }

    def action_workflow(self):
        return {
            'name': _('Approval Flow'),
            'type': 'ir.actions.act_window',
            'res_model': 'sb.workflow',
            'view_mode': 'form',
            'res_id': self.sb_workflow_id.id,
            'target': 'current',
        }

    def action_view_documents(self):
        self.ensure_one()
        dtl = {
            'name': 'Documents',
            'type': 'ir.actions.act_window',
            'res_model': 'documents.document',
            'view_mode': 'kanban,tree,form',
            'domain': [
                ('res_model', '=', 'equipment.requisition'),
                ('res_id', '=', self.id),
            ],
            'context': {
                'default_res_model': 'equipment.requisition',
                'default_res_id': self.id,
                'create': False,
            },
            'target': 'current',
        }
        if self.type == 'equipment':
            dtl['context']['default_folder_id'] = self.env.ref('sb_workflow_purchase.documents_eq_folder').id
        elif self.type == 'engineering':
            dtl['context']['default_folder_id'] = self.env.ref('sb_workflow_purchase.documents_en_folder').id
        return dtl

    def action_open_document_upload_wizard(self):
        self.ensure_one()
        dtl = {
            'type': 'ir.actions.act_window',
            'name': 'Upload Document',
            'res_model': 'documents.document',
            'view_mode': 'form',
            'target': 'new',
            'context': {
                'default_res_model': 'equipment.requisition',
                'default_res_id': self.id,
                'default_partner_id': self.user_id.partner_id.id,
            },
        }
        if self.type == 'equipment':
            dtl['context']['default_folder_id'] = self.env.ref('sb_workflow_purchase.documents_eq_folder').id
        elif self.type == 'engineering':
            dtl['context']['default_folder_id'] = self.env.ref('sb_workflow_purchase.documents_en_folder').id
        return dtl

    @api.constrains('sb_workflow_state')
    def _constrains_sb_workflow_state(self):
        for record in self.sudo():
            if record.state in ['draft']:
                continue
            if record.sb_workflow_state == 'approve':
                record.state = 'approved'
            elif record.sb_workflow_state == 'fail_to_approve':
                record.state = 'rejected'


class EquipmentType(models.Model):
    _name = 'equipment.type'

    name = fields.Char(string="Equipment Type")
